<template>
  <div>
    <Header activeClass="1" @findService="getfindService"  @apisum="getapisum" @xslxwm="xslxwm"></Header>
    <div class="wid" id="apilbox">
      <div id="apileft">
        <h2  @click="showList(-1)" style="cursor: pointer;">API大全</h2>
        <ul>
          <!-- 分类 -->
          <li v-for="item in categories" :key="item.id"   @click="showList(item.id,item.name)">
           <a href="javascript:;" :id="item.id" :class="{ on:changeRed == item.id}" > {{ item.name }}
            <span>{{ item.serviceNum }}</span>
            </a>
          </li>
        </ul>
      </div>

      <!-- 内容 -->
      <div id="apiright">
        <div id="cp_list" v-if="!cont">


          <div id="apirtitle"  v-if="sfsy">
            <h1>
              全部API
              <span>{{apisum}}个</span>
            </h1>
            <div class="clearfix"></div>
          </div>


          <div id="topcrumb" class="wid"  v-if="!sfsy">
            <a href="javascript:;" @click="showList(-1)">全部API</a>
            <span></span>{{rjn}} ({{apisum}}个)
          </div>

          <div id="apilistbox" class="hotdata">

            <div class="search_no" v-if="!searchon">
              <img src="../../assets/images/no.png">
            </div>

            <ul>

              <!-- 列表 -->
              <li v-for="item in findService" :key="item.id" :style="{'border-top-color':(item.color?item.color:'#00B0FE')}"  @click="showCont(item.id)">
                <a href="javascript:;">
                  <!-- <div class="apitag apifree"></div>
                  <div class="apicom">官方</div> -->
                  <img :src="item.cover" height="70" :alt="item.name" />
                  <h3>{{ item.name }}</h3>
                  <span>
                    <!-- <i class="nocalprice">{{ item.isFree?"免费":"收费"}}</i> -->
                  </span>
                  <div class="apinum">
                    <span class="clicknum">
                      <i></i>{{ item.view }}
                    </span>
                    <span class="usenum">
                      <i></i>{{ item.invoke }}
                    </span>
                  </div>
                </a>
              </li>

            </ul>
            <div class="clearfix"></div>
          </div>

        </div>

        <div id="cp_cont" v-if="cont">
          <div id="topcrumb" class="wid">
            <a href="javascript:;" @click="showList(-1)">全部API</a>
            <span></span>
            <a href="javascript:;" @click="showList(serviceDetail.categoryId,serviceDetail.categoryName)">{{serviceDetail.categoryName}}</a>
            <span></span>{{serviceDetail.name}}
          </div>
          <div id="apiileft">
            <div id="apiinfo"  :style="{'border-top-color':(serviceDetail.color?serviceDetail.color:'#00B0FE')}" >
              <div id="apiinfoleft">
                <img
                  :src="serviceDetail.cover"
                  height="70"
                  :alt="serviceDetail.name"
                />
 
              </div>
              <div id="apiinforight">
                <div id="apiitop">
                  <h1>{{serviceDetail.name}}</h1>
                  <input type="hidden" id="serviceInfo_sn" value="NEWS" />
                  <div class="clearfix"></div>
                </div>
                <div id="apiiprice">
                  <!-- <span class="isfree">{{ serviceDetail.isFree?"免费":"收费"}}</span> -->
                </div>
                <div id="apiidesc">{{serviceDetail.desc}}</div>
                <div id="apinuminfo">
                  <ul>
                    <li>
                      查看数：
                      <span id="aninum1">{{ serviceDetail.view }}</span>
                    </li>
                    <li>
                      使用数：
                      <span id="aninum2">{{ serviceDetail.invoke }}</span>
                    </li>
                  </ul>
                  <div class="clearfix"></div>
                </div>
                <div id="apiicollect">
                  <a
                    href="javascript:;"
                    rel="nofollow"
                    id="applybtn"
                    @click="showsq(serviceDetail.id,serviceDetail.name)"
                  >申请服务</a>
                  <div class="clearfix"></div>
                </div>
              </div>
              <div class="clearfix"></div>
            </div>
            <div id="apicontent">
              <div id="apitab">
                <ul>
                  <li>
                    <a href="javascript:;" class="on">API</a>
                  </li>
                </ul>
                <div class="clearfix"></div>
              </div>
              <div id="apibox">
                <div id="apimain" style="display: block;">
                  <input type="hidden" id="type" value="1" />
                  <!-- 不为空	 -->
                  <div id="apibleft">
                    <ul>
                      <li v-for="(item,index) in serviceDetail.serviceApis" :key="item.id"   @click="showAPIList(index)">
                        <a href="javascript:;" :id="item.id" :class="{ on:changeshowAPIList == index}" > {{ item.name }}</a>
                      </li>
                    </ul>
                  </div>

                  <div id="apibright" style="width:620px">
                    <input type="hidden" id="size" value="5" />
                    <div class="subapiitem2" style>
                      <!-- <input type="hidden" value="0"> -->
                      <div class="subapiinfo">
                        <div class="apiline">
                          <label>接口地址：</label>
                          <span
                            class="enword lightblue"
                          >{{showAPI.urlPrefix}}{{showAPI.url}}</span>
                        </div>
                      </div>
                      <div class="apiline">
                        <label>返回格式：</label>
                        <span class="enword">JSON</span>
                      </div>
                      <div class="apiline">
                        <label>请求方法：</label>
                        <span class="enword">{{showAPI.method}}</span>
                      </div>
                      <div class="apiline">
                        <label>请求示例：</label>
                        <span
                          class="enword lightblue"
                        >{{showAPI.urlPrefix}}{{showAPI.requestExample}}</span>
                      </div>
                      <div class="apilinebox">
                        <div class="alh4line">
                          <h4>请求参数：</h4>
                        </div>
                        <table>
                          <tbody>
                            <tr>
                              <th class="col1">参数名称</th>
                              <th class="col2">类型</th>
                              <th class="col3">必填</th>
                              <th class="col4">说明</th>
                            </tr>

                         

                            <tr v-for="item in showAPI.params" :key="item.id">
														<td class="param">{{item.name}}</td>
														<td class="param">{{item.type}}</td>
														<td>{{item.required == "Y"?"是":"否"}}</td>
														<td>{{item.desc}}</td>
													  </tr>

                          </tbody>
                        </table>
                      </div>
                      <div class="coderesponse">
                        <h4>JSON返回示例 :</h4>
                        <div class="codeboxresponse">
                             <json-viewer :value="showAPIJSON" :expand-depth=5
      copyable
      boxed
      sort></json-viewer>
                        </div>
                      </div>
                    </div>

                    <div class="clear"></div>
                  </div>

                </div>
              </div>
              <div class="clear"></div>
            </div>
          </div>
        </div>
      </div>


<!-- 申请 -->
      <div class="sq_box" v-if="sq">
        <div
          class="layui-layer-shade"
          id="layui-layer-shade100001"
          @click="gbsq"
          style="width:100%;height:100%; z-index:19991014; background-color:#000; opacity:0.65; filter:alpha(opacity=65);"
        ></div>

        <div
          class="layui-layer layui-layer-page layer-anim"
          id="layui-layer1"
          type="page"
          times="1"
          showtime="0"
          contype="object"
          style="z-index: 19891015;
    width: 400px;
    height: 570px;
    top: 50%;
    left: 50%;
    position: fixed;
    margin: -270px 0 0 -200px;"
          v-if="sq"
        >
          <div id class="layui-layer-content" style="height: 570px;">
            <div
              class="registerMain layui-layer-wrap"
              id="addapi"
              style="display: block;background: #ffffff;"
            >
              <div class="regDiv">
                <div class="xTitle">
                  <h4 class="emailTitle">申请服务</h4>
                  <a class="closeA" href="javascript:;" @click="gbsq">×</a>
                </div>


             <div class="sqcg" v-if="sqcg">
                <img src="../../assets/images/sqcg2.png">
                <span>申请成功</span>
             </div> 

    <div class="regForm" v-if="!sqcg">
                      <input type="hidden" id="serviceName" value="天气指数服务" />

                 

                  <div class="inputDiv">
                    <input
                      type="text"
                      class="regInput"
                      name="projectName"
                      id="projectName"
                      placeholder="项目名称"
                      tabindex="2"
                      autocomplete="off"
                      v-model="projectName"
                    />
                  </div>

                  <div class="inputDiv">
                    <input
                      type="text"
                      class="regInput"
                      name="client"
                      id="client"
                      placeholder="客户（整车厂）"
                      tabindex="2"
                      autocomplete="off"
                      v-model="client"
                    />
                  </div>

                  <div class="inputDiv">
                    <input
                      type="text"
                      class="regInput"
                      name="projectManager"
                      id="projectManager"
                      placeholder="项目经理"
                      tabindex="2"
                      autocomplete="off"
                      v-model="projectManager"
                    />
                  </div>

                 

                  <div class="inputDiv">
                    <div style="margin-bottom: 10px;display: block;">
                      用途：

                   
                      <div class="labelRight" >

                        <el-radio-group v-model="radioTreaty" @change="agreeChange">
                            <el-radio label="1" >测试</el-radio>
                            <el-radio label="2" >商用</el-radio>
                        </el-radio-group>

                      </div>

                    </div>

                    <b class="label_test_text"   v-if="radioTreaty==1">测试使用时间为3个月！</b>

                    <p class="label_commercial"  v-if="radioTreaty==2">
                      <em>{{sqyear}}</em>
                      <input
                        type="number"
                        id="year"
                        class="regInput label_number"
                        max="9"
                        min="3"
                        v-model="sqyear"
                      />
                      <span class="label_number_text">年</span>
                    </p>

                  </div>

                  <div class="forgetA" style="height: auto;">
                    <p class="errorTips" v-if="formmsg">
                      <i></i>
                      <em>{{formmsg}}</em>
                    </p>
                    <div class="sysError" style="display: none;">
                      <i></i>
                      <em></em>
                    </div>
                  </div>

                  <b class="label_instruction_text">*车辆唯一识别码sn必须真实上传，若随意上传本平台有权停用该appkey！</b>

                  <div class="inputDiv login-button-div" @click="sqapi(serviceDetail.sn,serviceDetail.name)">
                    <input
                      type="button"
                      class="regBtn"
                      id="postBtn"
                      value="提交"
                      style="letter-spacing: 3px;"
                    />
                  </div>

                  </div>

              </div>
            </div>
          </div>
          <span class="layui-layer-setwin"></span>
          <span class="layui-layer-resize"></span>
        </div>
      </div>

      <div class="clearfix"></div>
    </div>

    <Footer :khxs="khxs" :lxwm="lxwm" @xslxwm="xslxwm"  @gblxwm="gblxwm"></Footer>
  </div>
</template>
  
<script>
import Header from "../common/Header";
import Footer from "../common/Footer";
import qs from 'qs';
import axios from 'axios';

export default {
  name: "Index",
  components: { Header, Footer},
  data() {
    return {
      khxs:true,
      lxwm:false,
      cont: false,
      sq: false,
      changeRed:-1,
      apisum:0,
      categories: [],
      findService:[],
      serviceDetail:"",
      changeshowAPIList:0,
      showAPI:[],
      showAPIJSON:"",
      searchon:true,
      selectStatus:'',
      sqyear:3,
      projectName:"",
      projectManager:"",
      client:"",
      sqcg:false,
      formmsg:"",
      radioTreaty: '0',
      sfdl:false,
      uname:"个人中心",
      sfsy:true,
      rjn:"",
      ip:''
    };
  },
// http://localhost:8081/#/?apiid=5ed0cb22c98e372884e133f9
  mounted: function() {

    var _this = this;

_this.getUserIP((ip) => {

        // 打印客户端ip

       console.log(ip);

      _this.ip = ip;

    });


    
    console.log("aaaa",_this.$route.query.id);
    if(_this.$route.query.id){
     _this.postbox(_this.$route.query.id);
    }else{

      var cc = localStorage.getItem("search_ip");
      console.log("search_ip",cc);
      if(cc == null){
        _this.initNav();
      }
      else{

        
                _this.$http({
                  url: "index/search?key=" + cc,
                  method: "get"
                }).then(res => {
                  console.log(res.data);


                  _this.findService = res.data.datas;
                _this.apisum = res.data.datas.length;
                _this.apisum == 0?_this.searchon=false:_this.searchon=true;


                  document.querySelector("#apilbox2").scrollIntoView(true)
                  localStorage.removeItem("search_ip");

                });
   

      }
      
      

    }
    
    
    var utoken = localStorage.getItem("USER_TOKEN");
    console.log("utoken",utoken);
    
    if(utoken){
      this.sfdl = true;
      var una = localStorage.getItem("USER");
      una = JSON.parse(una)
      console.log(una.username);
      this.uname = una.username;
    }

    localStorage.removeItem("preurl");


  },



  methods: {



    //获取网页访问ip

getUserIP(onNewIP) {

      let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;

      let pc = new MyPeerConnection({

        iceServers: []

      });

      let noop = () => {

      };

      let localIPs = {};

      let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;

      let iterateIP = (ip) => {

        if (!localIPs[ip]) onNewIP(ip);

        localIPs[ip] = true;

      };

      pc.createDataChannel('');

      pc.createOffer().then((sdp) => {

        sdp.sdp.split('\n').forEach(function (line) {

          if (line.indexOf('candidate') < 0) return;

          line.match(ipRegex).forEach(iterateIP);

        });

        pc.setLocalDescription(sdp, noop, noop);

      }).catch((reason) => {

      });

      pc.onicecandidate = (ice) => {

        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;

        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);

      };

},

        gblxwm: function() {
      this.lxwm = false;
    },
        xslxwm: function() {
        console.log(1232132132);
        this.lxwm = true;
    },

    agreeChange:function(val){
          let that = this 

          console.log(val);
          that.radioTreaty = val
          
        },

  // 申请
  sqapi(id,name){
     let _this = this;
     console.log(id,name,_this.projectName,_this.projectManager,_this.client,_this.radioTreaty,_this.sqyear);
     if(id&&name&&_this.projectName&&_this.projectManager&&_this.client&&_this.radioTreaty&&_this.sqyear){

        let stype = "";
        _this.radioTreaty == 1 ? stype="test" : stype="buss";
        
        console.log(id,name,_this.projectName,_this.projectManager,_this.client,stype,_this.sqyear);

        var utoken = localStorage.getItem("USER_TOKEN");
        var data = {
          "serviceSn":id,
          "serviceName":name,
          "projectName":_this.projectName,
          "projectManager":_this.projectManager,
          "client":_this.client,
          "type":stype,
          "year":`${_this.sqyear}`,
        }

      console.log(utoken);
      utoken = utoken.replace('"', ''); 
      utoken = utoken.replace('"', ''); 
      console.log(utoken);





      this.$http({
        url: `check/add`,
        method: 'post',
        headers: {
          
          "Authentication":utoken,
          'Content-Type': 'application/x-www-form-urlencoded'
          
          },
        data: qs.stringify(data)
      }).then(res => {
        console.log("申请：",res);
        if(res.data.code == "1"){
          _this.sqcg = true;
        }else{
          _this.formmsg = res.data.msg;
        }

        

        

      }).catch(function (error) {
       
        console.log("aaa:",error);
        if(error == "Error: Request failed with status code 401"){
         _this.formmsg = "您的账号在其他设备登录账号信息已过期请重新登录";
        //  localStorage.removeItem("USER_TOKEN");
        //  _this.sfdl = false;
         console.log(2222);
        }
    });

     }else{
       this.formmsg = "请全部填写完整后提交";
     }
     
  },


  getfindService(title){
  this.findService=title;
  },

  getapisum(title){
    console.log(12321321321312);
    
    this.cont=false;
    this.apisum=title;
    title == 0?this.searchon=false:this.searchon=true;
  },

    showsq: function(id) {
      console.log("apiid:",id);

      var utoken = localStorage.getItem("USER_TOKEN");
      console.log("token",utoken);


      
      
      if(utoken != null){

        utoken = utoken.replace('"', ''); 
        utoken = utoken.replace('"', ''); 
        console.log(utoken);

        this.$http.get(`index/validToken?token=${utoken}`).then(res => {
          console.log("index/validToken?token=:",res);
          if(res.data){
            this.sq = true;
          }else{
            var ta = window.location.href+"?id="+id;
            localStorage.setItem("preurl",ta);
            window.location.href ="https://dainfo.hsaeyz.cn:9046/data-center/#/login?url="+ta;
          }
          
          
        });

        
      }else{
        
        var ta = window.location.href+"?id="+id;
        localStorage.setItem("preurl",ta);
        window.location.href ="https://dainfo.hsaeyz.cn:9046/data-center/#/login?url="+ta;
        
      }

    },

    gbsq: function() {
      this.sq = false;
      this.sqcg = false;
      this.formmsg = "";


        this.client = "";
             this.projectName = "";
      this.projectManager = "";
   this.radioTreaty= '0';

      this.sqyear = 3;
 
  
    },

    //登录返回后显示
    postbox(id){
      this.khxs = false;
      console.log("23423423432",this.khxs);
      
      this.showCont(id);
    },

    // 获取分类
    initNav() {
      let _this = this;
      this.$http.get("index/findCategory").then(res => {
        console.log("categories:",res.data.datas);
        _this.categories = res.data.datas;
      });
      this.list(-1);
    },

    // 选择分类
    showList:function(id,name){
      this.changeRed = id;
      this.cont = false;
      this.rjn = name;
     
      this.list(id);
    },


    // 获取列表
    list(id) {
      
      let _this = this;

      if(id == "-1"){
        _this.sfsy = true

      }else{
        _this.sfsy = false
      }

      this.$http({
        url: 'index/findService?categoryId='+id,
        method: 'get'
      }).then(res => {
        console.log(res.data);
        _this.findService = res.data.datas;
        _this.apisum = res.data.datas.length;
        _this.apisum == 0?_this.searchon=false:_this.searchon=true;
      })
    },

    // 显示详情
    showCont: function(id) {
      
         this.khxs = false;
      console.log("23423423432",this.khxs);
      let _this = this;
      this.$http({
        url: 'index/serviceDetail?serviceId='+id+'&ip='+_this.ip,
        method: 'get'
      }).then(res => {
        let serviceDetail = res.data.datas;
        console.log(res.data);
        _this.serviceDetail = serviceDetail;
        _this.cont = true;
        _this.showAPI = _this.serviceDetail.serviceApis[0];
        
        
        _this.showAPIJSON = JSON.parse(_this.showAPI.returnExample)
        console.log(_this.showAPIJSON);
      })
    },

    // 选择API
    showAPIList:function(index){
      this.changeshowAPIList = index;
      this.showAPI = this.serviceDetail.serviceApis[index];
      this.showAPIJSON = JSON.parse(this.showAPI.returnExample);
    },

  }
};
</script>
<style lang="less" scoped>
.sq_box {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
}
.labelRight {
  display: inline-block;
  margin: 0 0 0 10px;
}
.userLabelRadio {
  margin-right: 10px;
}
#addapi .inputDiv .label_number {
  width: 220px;
}
.label_number_text {
  margin-left: 10px;
}
.label_test_text {
  color: #fe514a;
  font-size: 14px;

}
.label_commercial {
  position: relative;
}
.label_commercial em {
  position: absolute;
  top: 1px;
  left: 1px;
  width: 180px;
  height: 38px;
  padding: 0 10px;
  background: #ffffff;
  color: rgb(102, 102, 102);
  font-style: normal;
  line-height: 40px;
}
</style>